﻿/**
 * Create on 2012-1-4
 */
package kit4j.tests.jdk.awt;

import java.awt.AWTException;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * @author 吴政
 * 
 */
public class TestPrintScreenWithRobot {

	private static int count = 0;

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				final JFrame frame = new JFrame();
				final JButton btn = new JButton("PrintScreen");
				final Robot robot = createRobot();
				final String filePrefix = "Screenshot";

				btn.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						BufferedImage image = robot.createScreenCapture(new Rectangle(
								frame.getLocationOnScreen(), frame.getSize()));

						File output = new File(filePrefix + " - " + count
								+ ".jpg");

						System.out.println("start write image to \""
								+ output.getAbsolutePath() + "\"...");

						try {
							if (!ImageIO.write(image, "jpg", output)) {
								throw new Exception("Not found \"jpg\" writer!");
							}
							
							++count;

							System.out.println("successed!");
						} catch (Exception e) {
							e.printStackTrace();

							System.out.println("failed.");
						}

						System.out.println("end write image...");
					}
				});

				frame.setSize(500, 300);
				frame.setLocationRelativeTo(null);
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				frame.setLayout(new FlowLayout());

				frame.add(btn);

				frame.setVisible(true);
			}
		});
	}

	private static Robot createRobot() {
		try {
			return new Robot();
		} catch (AWTException e) {
			e.printStackTrace();

			return null;
		}
	}
}
